package com.ext.aic.ui;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.TypedValue;
import android.view.View;

import com.ext.aic.AICApplication;
import com.ext.aic.R;
import com.ext.aic.apis.attachment.GenerateImageRequest;
import com.ext.aic.beans.params.GenerateImageParams;
import com.ext.aic.beans.response.GenerateImageResponse;
import com.ext.aic.components.AnimatedGradientDrawable;
import com.ext.aic.constants.EBusConstants;
import com.ext.aic.databinding.AiGenerateImageLayoutBinding;
import com.ext.aic.utils.ToastyUtils;
import com.ext.aic.utils.UserUtils;
import com.eyinfo.android_pure_utils.ebus.EBus;
import com.eyinfo.android_pure_utils.utils.GlobalUtils;
import com.eyinfo.storage.files.FileUtils;

import java.io.File;

import io.github.eyinfo.okrx.DownloadManager;
import io.github.eyinfo.okrx.events.OnDownloadSuccessAction;

public class AIGenerateImageActivity extends BaseActivity {

    private AiGenerateImageLayoutBinding binding;
    private AnimatedGradientDrawable gradientDrawable = new AnimatedGradientDrawable();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        View view = View.inflate(this, R.layout.ai_generate_image_layout, null);
        binding = AiGenerateImageLayoutBinding.bind(view);
        initView();
        setContentView(binding.getRoot());

        float radiusInPx = TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP,
                8,
                getResources().getDisplayMetrics()
        );
        gradientDrawable.setCornerRadius(radiusInPx);
        binding.aiImageRiv.setBackground(gradientDrawable);
    }

    private void initView() {
        binding.topView.backIv.setOnClickListener((view) -> finish());
        binding.topView.titleTv.setText(R.string.ai_generate_image);
        binding.mainBtn.setOnClickListener(this::onMainClick);
        binding.cancelBtn.setOnClickListener(this::onCancelClick);
        binding.aiGenerateImageTextEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String text = s.toString();
                binding.mainBtn.setEnabled(!TextUtils.isEmpty(text));
            }
        });
    }

    public void onCancelClick(View v) {
        finish();
    }

    public void onMainClick(View v) {
        String message = binding.aiGenerateImageTextEt.getText().toString();
        if (TextUtils.isEmpty(message)) {
            ToastyUtils.getInstance().show(getString(R.string.generate_image_hint));
            return;
        }
        gradientDrawable.start();
        binding.aiGenerateImageTextEt.setEnabled(false);
        binding.interrupGenerationRl.setVisibility(View.VISIBLE);
        binding.mainBtn.setEnabled(false);
        String userId = UserUtils.getInstance().getUserId();
        GenerateImageParams generateImageParams = new GenerateImageParams(userId, message);
        generateImageRequest.request(this, this, generateImageParams);
    }

    private String getImageFileName(String imageUrl) {
        if (TextUtils.isEmpty(imageUrl)) {
            return String.format("%s.jpg", GlobalUtils.getNewGuid());
        }
        int index = imageUrl.indexOf("?");
        if (index > 0) {
            return FileUtils.getName(imageUrl.substring(0, index));
        } else {
            return FileUtils.getName(imageUrl);
        }
    }

    private GenerateImageRequest generateImageRequest = new GenerateImageRequest() {
        @Override
        protected void onGenerateImageSuccess(GenerateImageResponse response) {
            String imageUrl = response.getImageUrl();

            File cacheDir = AICApplication.getInstance().getCacheDir();
            File dir = FileUtils.createDirectory(cacheDir, "images");
            File file = new File(dir, getImageFileName(imageUrl));
            if (!file.exists()) {
                try {
                    boolean newFile = file.createNewFile();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            DownloadManager.getInstance().download(imageUrl, file, new OnDownloadSuccessAction() {
                @Override
                public void call(File file) {
                    int nineTag = getBundleInt("nineTag");
                    EBus.getInstance().post(EBusConstants.receiveAiGenerateImage, nineTag, file.getName(), file.getAbsolutePath());
                    finish();
                }
            });
        }

        @Override
        protected void onGenerateImageEnd() {
            super.onGenerateImageEnd();
            binding.aiGenerateImageTextEt.setEnabled(true);
            binding.interrupGenerationRl.setVisibility(View.GONE);
            binding.mainBtn.setEnabled(true);
            gradientDrawable.stop();
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        gradientDrawable.stop();
    }
}
